﻿namespace JxcLite.Pages.BillData;

partial class BillForm
{
    private IBaseDataService BaseData;
    private IBillService Service;
    private KUpload upload;
    private List<JxGoods> Goodses = [];

    private List<CodeInfo> GoodsCodes => Goodses?.Select(c => new CodeInfo(c.Code, c.Name)).ToList();

    protected override async Task OnInitFormAsync()
    {
        await base.OnInitFormAsync();
        BaseData = await CreateServiceAsync<IBaseDataService>();
        Service = await CreateServiceAsync<IBillService>();
    }

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        await base.OnAfterRenderAsync(firstRender);
        if (firstRender)
        {
            Goodses = await BaseData.GetGoodsesAsync();
            if (Model.Data.Lists == null || Model.Data.Lists.Count == 0)
                Model.Data.Lists = await Service.GetBillListsAsync(Model.Data.Id);
        }
    }

    private static string GetPartnerPickerType(JxBillHead model)
    {
        if (model.Type == BillType.Import || model.Type == BillType.ImportReturn)
            return PartnerType.Supplier;
        else if (model.Type == BillType.Export || model.Type == BillType.ExportReturn)
            return PartnerType.Customer;
        return string.Empty;
    }

    private async Task OnFilesChangedAsync(List<FileDataInfo> files)
    {
        if (Model.Data.IsNew)
        {
            Model.Files[nameof(JxBillHead.Files)] = files;
        }
        else
        {
            Model.Files[nameof(JxBillHead.Files)] = files;
            await Model.SaveAsync(d => upload.SetValueAsync(d.Files), false);
        }
    }

    private void OnAdd()
    {
        Model.Data.Lists.Add(new JxBillList
        {
            HeadId = Model.Data.Id,
            SeqNo = Model.Data.Lists.Count + 1
        });
    }

    private void OnDelete(JxBillList row) => Model.Data.Lists.Remove(row);

    private void OnGoodsChange(CodeInfo item, JxBillList row)
    {
        var data = Goodses?.FirstOrDefault(g => g.Code == item?.Code);
        row.Code = data?.Code;
        row.Name = data?.Name;
        row.Category = data?.Category;
        row.Model = data?.Model;
        row.Producer = data?.Producer;
        row.Unit = data?.Unit;
    }

    private void OnGoodsChange(int field, JxBillList row)
    {
        if (field == 1 || field == 2)
            row.Amount = Utils.Round((row.Qty * row.Price) ?? 0, 2);
        else if (field == 3 && row.Qty > 0)
            row.Price = Utils.Round((row.Amount / row.Qty) ?? 0, 2);
        Model.Data.TotalAmount = Model.Data.Lists.Sum(l => l.Amount);
    }
}